(function ($) {
    $.fn.amount = function (options) {
        var defaults = {
                    max: "data-max",
                    min: "data-min"
                };
        var opts = $.extend(defaults, options);
        
        var lessOrMost = function(obj) {
            obj.addClass('disabled').siblings().removeClass('disabled');
        };

        return $.each(this, function () {
            var inputObj = $(this),max = inputObj.attr(opts.max),min = inputObj.attr(opts.min),
            parent = $('<div class="amount"></div>'),
            minus = $('<span class="amount-minus">-</span>'),
            plus = $('<span class="amount-plus">+</span>');
            
            var events = inputObj.data('events')['blur'];
            minus.click(function(){
                var val = inputObj.val();
                if(parseInt(val) > 0 || typeof min === 'undefined' || min==='' || val>min) {
                    inputObj.val(parseInt(val)-1);
                } else {
                    lessOrMost($(this));
                }
            }).dblclick(function(e){e.stopPropagation();});
            plus.click(function(){
                var val = inputObj.val();
                if(typeof max === 'undefined' || max==='' || val<max) {
                    inputObj.val(parseInt(val)+1);
                } else {
                    lessOrMost($(this));
                }
            }).dblclick(function(e){e.stopPropagation();});
            inputObj.keyup(function(){
                var _this = $(this);
                var val = _this.val().replace(/[^\d]/g, '');
                if(typeof max !== 'undefined' && max !== '' && val > max) {
                    val = max;
                } else if(typeof min !== 'undefined' && min !== '' && val < min) {
                    val = min;
                } else if(val === '') {
                    val = 0;
                }
                _this.val(val);
            });
            inputObj.addClass('amount-input').wrap(parent);
            minus.insertBefore(inputObj);
            plus.insertAfter(inputObj);
        });
    };
})(jQuery);  	